package com.wjk.kylin.modules.system.controller;


import com.wjk.kylin.core.common.aspect.Log;
import com.wjk.kylin.core.common.controller.BaseController;
import com.wjk.kylin.core.common.data.ResponseData;
import com.wjk.kylin.core.common.oshi.server.Server;
import com.wjk.kylin.core.common.oss.OSSFileModel;
import com.wjk.kylin.core.common.oss.OSSServerImpl;
import com.wjk.kylin.core.common.valid.update;
import com.wjk.kylin.core.constant.Constants;
import com.wjk.kylin.core.security.TokenUtil;
import com.wjk.kylin.core.utils.AliCloudOSSUtils;
import com.wjk.kylin.core.utils.SecurityUtils;
import com.wjk.kylin.modules.system.dept.entity.Dept;
import com.wjk.kylin.modules.system.dept.service.IDeptService;
import com.wjk.kylin.modules.system.position.entity.Position;
import com.wjk.kylin.modules.system.position.service.IPositionService;
import com.wjk.kylin.modules.system.role.entity.Role;
import com.wjk.kylin.modules.system.role.service.IRoleService;
import com.wjk.kylin.modules.system.user.entity.User;
import com.wjk.kylin.modules.system.user.service.IUserPositionService;
import com.wjk.kylin.modules.system.user.service.IUserRoleService;
import com.wjk.kylin.modules.system.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.wjk.kylin.core.constant.CommonConstant.BusinessType.LIST;
import static com.wjk.kylin.core.constant.CommonConstant.BusinessType.UPDATE;

/**
 * @author wangjkui
 * @description 通用控制器
 * @date 2020/5/22
 */
@Api("系统")
@Slf4j
@Validated
@RestController
@RequestMapping("/sys/system")
public class SystemController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IUserPositionService userPositionService;
    @Autowired
    private TokenUtil jwtTokenUtil;
    @Autowired
    private OSSServerImpl ossServer;


    @ApiOperation("个人信息")
    @GetMapping("/userInfo")
    public ResponseData profile() {
        String userId = SecurityUtils.getUserId();
        //用户信息
        User user = userService.getById(userId);
        Dept dept = deptService.getById(user.getDeptId());
        user.setDeptName(dept.getName());

        List<String> roleIds = userRoleService.findRoleListByUserId(userId);
        List<String> positionIds = userPositionService.findPositionListByUserId(userId);

        List<Role> roleList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roleIds)) {
            roleList = roleService.listByIds(roleIds);
        }
        String roleNames = String.join(",", roleList.stream().map(Role::getName).collect(Collectors.toList()));

        List<Position> positionList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roleIds)) {
            positionList = positionService.listByIds(positionIds);
        }
        String positionNames = String.join(",", positionList.stream().map(Position::getName).collect(Collectors.toList()));

        Map<String, Object> map = new HashMap<>(3);

        map.put("user", user);
        map.put("roleNames", roleNames);
        map.put("positionNames", positionNames);

        return ResponseData.success().data(map);
    }

    @ApiOperation("修改用户")
    @Log(title = "个人中心-修改用户", businessType = UPDATE)
    @PutMapping("/userEdit")
    public ResponseData updateProfile(@Validated(update.class) @RequestBody User user) {

        user.setId(SecurityUtils.getUserId());
        user.preUpdate();

        boolean flag = userService.updateById(user);

        if (flag) {
            return ResponseData.success();
        }
        return ResponseData.error("修改个人信息异常，请联系管理员");
    }

    @ApiOperation("重置密码")
    @Log(title = "个人中心-重置密码", businessType = UPDATE)
    @PutMapping("/updatePwd")
    public ResponseData updatePwd(@NotBlank(message = "旧密码不能为空") @RequestParam("oldPassword") String oldPassword,
                                  @NotBlank(message = "新密码不能为空") @RequestParam("newPassword") String newPassword) {
        String userId = SecurityUtils.getUserId();
        User user = userService.getById(userId);

        if (!SecurityUtils.matchesPassword(oldPassword, user.getPassword())) {
            return ResponseData.error("修改密码失败，旧密码错误");
        } else if (SecurityUtils.matchesPassword(newPassword, user.getPassword())) {
            return ResponseData.error("新密码不能与旧密码相同");
        }

        boolean flag = userService.resetPwd(user.getId(), newPassword);

        if (flag) {
            // 删除token，强制用户重新登录
            jwtTokenUtil.removeTokenAndUser(user.getUserName());

            return ResponseData.success();
        }

        return ResponseData.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @ApiOperation("头像上传")
    @Log(title = "个人中心-头像上传", businessType = UPDATE)
    @PostMapping("/avatar")
    public ResponseData avatar(@RequestParam("avatarFile") MultipartFile file) {
        if (file != null && !file.isEmpty()) {
            String userId = SecurityUtils.getUserId();
            //用户信息
            OSSFileModel model = new OSSFileModel();
            model.setFile(file);
            String fileUrl = ossServer.uploadFile(model);
            if (StringUtils.isNotBlank(fileUrl) && userService.updateAvatar(userId, fileUrl)) {
                return ResponseData.success().data("imgUrl", fileUrl);
            }
        }
        return ResponseData.error("头像上传异常，请联系管理员");
    }

    @Log(title = "服务监控-列表", businessType = LIST, isSaveResponseData = false)
    @ApiOperation("服务监控")
    @PreAuthorize("hasAuthority('monitor:server:list')")
    @GetMapping("/monitor/server")
    public ResponseData getInfo() throws Exception {
        Server server = new Server();
        server.copyTo();
        return ResponseData.success().data("server", server);
    }


//    /**
//     * 测试文件上传
//     */
//    @PostMapping("/test")
//    public ResponseData test(@RequestParam("file") MultipartFile file) {
//        if (file != null && !file.isEmpty()) {
//            OSSFileModel model = new OSSFileModel();
//            model.setFile(file);
//            String fileUrl = ossServer.uploadFile(model);
//            if (StringUtils.isNotBlank(fileUrl)) {
//                return ResponseData.success().data("imgUrl", fileUrl);
//            }
//        }
//        return ResponseData.error("测试文件上传，请联系管理员");
//    }
}
